package com.xjoyt.pay.commons;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import com.xjoyt.pay.constants.DateConstant;

public final class ObjectUtils {

	/**
	 * 字段复制
	 * 
	 * @param src
	 * @param target
	 */
	public static void fieldCopy(Object src, Object target) {
		Class<?> srcClass = src.getClass();
		Class<?> targetClass = target.getClass();
		for (Field field : targetClass.getFields()) {
			for (Field srcField : srcClass.getFields()) {

				if (!srcField.getName().equals(field.getName())) {
					continue;
				}
				if (srcField.getType() == field.getType()) {
					try {
						Object value = srcField.get(src);
						field.set(target, value);
					} catch (Exception e) {
						e.printStackTrace();
					}
					continue;
				}

				if (srcField.getType() != String.class) {
					continue;
				}
				try {
					Object v = srcField.get(src);
					if (v == null) {
						field.set(target, v);
						continue;
					}
					String value = v.toString();
					if (field.getType() == Date.class) {
						Date date = DateUtils.parseDate(value, DateConstant.DATE_PARSE_PATTERNS);
						field.set(target, date);
						continue;
					}
					field.set(target, ConvertUtils.convert(value, field.getType()));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 修改字段
	 * 
	 * @param src
	 * @param name
	 * @param value
	 */
	public static void setFeild(Object src, String name, String value) {
		Class<?> cls = src.getClass();
		try {
			Field field = cls.getField(name);
			if (StringUtils.isEmpty(value)) {
				field.set(src, null);
			} else {
				Class<?> type = field.getType();
				if (Date.class.equals(type)) {
					field.set(src, DateUtils.parseDate(value.toString(), DateConstant.DATE_PARSE_PATTERNS));
				} else {
					field.set(src, ConvertUtils.convert(value, type));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static <T> Class<T> getGenericClass(Class<?> clz) {
		return getGenericClass(clz, 0);
	}

	public static <T> Class<T> getGenericClass(Class<?> clz, int index) {
		Type genericType = clz.getGenericSuperclass();

		if (!(genericType instanceof ParameterizedType)) {
			return null;
		}
		ParameterizedType pt = (ParameterizedType) genericType;
		Type[] types = pt.getActualTypeArguments();
		if (types.length < index + 1) {
			return null;
		}
		Type type = types[index];
		@SuppressWarnings("unchecked")
		Class<T> cls = (Class<T>) type;
		return cls;
	}
}
